package com.ambercrm.business.login;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.ambercrm.R;
import com.ambercrm.base.BaseActivity;
import com.ambercrm.business.main.MainActivity;
import com.ambercrm.business.webview.WebViewActivity;
import com.ambercrm.common.Common;
import com.ambercrm.constant.Constant;
import com.ambercrm.constant.UrlConstant;
import com.ambercrm.custom_view.ClearEditText;
import com.ambercrm.custom_view.TextInputLayout;
import com.ambercrm.tools.EmptyUtils;
import com.ambercrm.tools.LogUtils;

import org.json.JSONObject;

import java.util.HashMap;

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout llTitlePassword;
    private View passwordLine;
    private LinearLayout llTitleCode;
    private View codeLine;
    private LinearLayout llPasswordLogin;
    private TextInputLayout numberTextInputLayout;
    private ClearEditText etNumber;
    private TextInputLayout passwordTextInputLayout;
    private ClearEditText etPassword;
    private LinearLayout llCodeLogin;
    private TextInputLayout phoneNumberTextInputLayout;
    private ClearEditText etPhone;
    private TextInputLayout codeTextInputLayout;
    private ClearEditText etCode;
    private TextView tvGetCode;
    private Button btnLogin;
    private TextView tvUserProtocol;
    private TextView tvSecretPolicy;
    private CountDownTimer mCountDownTimer;
    private int type = 0;//0密码登录  1验证码登录

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        llTitlePassword = findViewById(R.id.ll_title_password);
        passwordLine = findViewById(R.id.password_line);
        llTitleCode = findViewById(R.id.ll_title_code);
        codeLine = findViewById(R.id.code_line);
        llPasswordLogin = findViewById(R.id.ll_password_login);
        numberTextInputLayout = findViewById(R.id.number_text_input_layout);
        etNumber = findViewById(R.id.et_number);
        passwordTextInputLayout = findViewById(R.id.password_text_input_layout);
        etPassword = findViewById(R.id.et_password);
        etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        llCodeLogin = findViewById(R.id.ll_code_login);
        phoneNumberTextInputLayout = findViewById(R.id.phone_number_text_input_layout);
        etPhone = findViewById(R.id.et_phone);
        codeTextInputLayout = findViewById(R.id.code_text_input_layout);
        etCode = findViewById(R.id.et_code);
        tvGetCode = findViewById(R.id.tv_get_code);
        btnLogin = findViewById(R.id.btn_login);
        tvUserProtocol = findViewById(R.id.tv_user_protocol);
        tvSecretPolicy = findViewById(R.id.tv_secret_policy);

        initListener();
        mCountDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tvGetCode.setClickable(false); //设置不可点击
                tvGetCode.setTextColor(getResources().getColor(R.color.common_color_d7d7d7));
                tvGetCode.setText(String.format(getResources().getString(R.string.get_code_time), millisUntilFinished / 1000 + "s"));  //设置倒计时时间
            }

            @Override
            public void onFinish() {
                tvGetCode.setClickable(true);
                tvGetCode.setTextColor(getResources().getColor(R.color.common_color_6c737c));
                tvGetCode.setText(R.string.send_identify_code);
            }
        };
    }

    private void initListener() {
        llTitlePassword.setOnClickListener(this);
        llTitleCode.setOnClickListener(this);
        tvGetCode.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        tvUserProtocol.setOnClickListener(this);
        tvSecretPolicy.setOnClickListener(this);
        etNumber.setOnTextChangeListener(new ClearEditText.OnTextChangeListener() {
            @Override
            public void onTextChange(String s) {
                checkBtnEnable();
            }
        });
        etPassword.setOnTextChangeListener(new ClearEditText.OnTextChangeListener() {
            @Override
            public void onTextChange(String s) {
                checkBtnEnable();
            }
        });
        etPhone.setOnTextChangeListener(new ClearEditText.OnTextChangeListener() {
            @Override
            public void onTextChange(String s) {
                String trim = s.trim();

                if (EmptyUtils.notEmpty(trim)) {
                    if (trim.length() == 11) {
                        tvGetCode.setClickable(true); //设置不可点击
                        tvGetCode.setTextColor(getResources().getColor(R.color.common_color_42CC8B));
                    } else {
                        tvGetCode.setTextColor(getResources().getColor(R.color.common_color_d2d4dd));
                    }
                }
                checkBtnEnable();
            }
        });
        etCode.setOnTextChangeListener(new ClearEditText.OnTextChangeListener() {
            @Override
            public void onTextChange(String s) {
                checkBtnEnable();
            }
        });


    }

    private void checkBtnEnable() {
        if (type == 0) {
            String number = etNumber.getText().toString().trim();
            String password = etPassword.getText().toString().trim();
            if (EmptyUtils.isEmpty(number)) {
                btnLogin.setEnabled(false);
                return;
            }

            if (EmptyUtils.isEmpty(password)) {
                btnLogin.setEnabled(false);
                return;
            }

            btnLogin.setEnabled(true);
        } else if (type == 1) {
            String phone = etPhone.getText().toString().trim();
            String code = etCode.getText().toString().trim();
            if (EmptyUtils.isEmpty(phone)) {
                btnLogin.setEnabled(false);
                return;
            }

            if (EmptyUtils.isEmpty(code)) {
                btnLogin.setEnabled(false);
                return;
            }

            btnLogin.setEnabled(true);
        }
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ll_title_password) {
            type = 0;
            passwordLine.setVisibility(View.VISIBLE);
            codeLine.setVisibility(View.GONE);
            llPasswordLogin.setVisibility(View.VISIBLE);
            llCodeLogin.setVisibility(View.GONE);
        } else if (id == R.id.ll_title_code) {
            type = 1;
            passwordLine.setVisibility(View.GONE);
            codeLine.setVisibility(View.VISIBLE);
            llPasswordLogin.setVisibility(View.GONE);
            llCodeLogin.setVisibility(View.VISIBLE);
        } else if (id == R.id.tv_get_code) {
            String phone = etPhone.getText().toString().trim();
            if (phone.length() == 11) {
                getCode();
            }
        } else if (id == R.id.btn_login) {
            passwordLogin();
        } else if (id == R.id.tv_user_protocol) {
            Bundle b = new Bundle();
            b.putString("url", UrlConstant.H5BaseUrl+"/user-agreement.html");
            b.putString("title", "用户协议");
            startActivity(WebViewActivity.class, b, false);
        } else if (id == R.id.tv_secret_policy) {
            Bundle b = new Bundle();
            b.putString("url", UrlConstant.H5BaseUrl+"/privacy-policy.html");
            b.putString("title", "用户协议");
            startActivity(WebViewActivity.class, b, false);
        }
    }

    private void getCode() {
        String phone = etPhone.getText().toString().trim();
        HashMap<String, String> params = new HashMap<>();
        params.put("phone", phone);
        httpPost(UrlConstant.GET_LOGIN_CODE_URL,1, params,  true, "");
    }

    private void passwordLogin() {
        if (type == 0) {
            String number = etNumber.getText().toString().trim();
            String password = etPassword.getText().toString().trim();
            if (EmptyUtils.notEmpty(number) && EmptyUtils.notEmpty(password)) {
                HashMap<String, Object> params = new HashMap<>();
                HashMap<String, Object> map = new HashMap<>();
                params.put("loginName", number);
                params.put("password", password);
                params.put("loginOrigin", "app");
                params.put("appcode", "HP-CRM");
                params.put("clTerminal", "android");
                params.put("noLandingDays", 30);
                params.put("isApplogin", true);
                params.put("modelKey", "");
                params.put("tenantid", "");
                map.put("ssoadminLogindto", params);
                httpPost(UrlConstant.LOGIN_URL, 0, map, true, "");
            }
        } else if (type == 1) {
            String phone = etPhone.getText().toString().trim();
            String code = etCode.getText().toString().trim();
            if (EmptyUtils.notEmpty(phone) && EmptyUtils.notEmpty(code)) {
                HashMap<String, Object> params = new HashMap<>();
                HashMap<String, Object> map = new HashMap<>();
                params.put("loginPhone", phone);
                params.put("captcha", code);
                params.put("loginOrigin", "phoneapp");
                params.put("appid", "SSO");
                params.put("clTerminal", "android");
                params.put("noLandingDays", 30);
                map.put("ssoadminLogindto", params);
                httpPost(UrlConstant.PHONE_LOGIN_URL, 0, map, true, "");
            }
        }
    }

    @Override
    protected void onSucceed(String result, int what) {
        super.onSucceed(result, what);
        try {
            if (what == 0) {
                JSONObject object = new JSONObject(result);
                String code = object.optString("code");
                String msg = object.optString("msg");
                JSONObject data = object.optJSONObject("result");

                if ("0".equals(code)) {
                    JSONObject authObj = data.getJSONObject("auth");
                    String realName = authObj.optString("realname");
                    sp.putValue(Constant.sp_realName, realName);

                    String token = data.optString("token");
                    sp.putValue(Constant.sp_Token, token);
                    Common.getInstance().setToken(token);
                    startActivity(MainActivity.class, null, true);
                } else {
                    toast(msg);
                }
            } else if (what == 1) {
                JSONObject object = new JSONObject(result);
                String code = object.optString("code");
                String msg = object.optString("msg");
                if ("0".equals(code)) {
                    mCountDownTimer.start();
                } else {
                    toast(msg);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mCountDownTimer.cancel();
    }
}
